package dev.alm.java11boot276.utils;

import org.springframework.beans.factory.annotation.Value;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtil {

    private static volatile JedisPool jedisPool = null;

    @Value("${spring.redis.host}")
    private static String host;

    @Value("${spring.redis.port}")
    private static int port;

//    private JedisUtil() {}

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig config = new JedisPoolConfig();
                    config.setMaxTotal(200);
                    config.setMaxIdle(32);
                    config.setMaxWaitMillis(100 * 1000);
                    config.setBlockWhenExhausted(true);
                    config.setTestOnBorrow(true);       // ping PONG
                    jedisPool = new JedisPool(config, host, port);
                }
            }
        }
        return jedisPool;
    }

    public static void release(Jedis jedis) {
        if (null != jedis) {
            jedis.close();
        }
    }

    public static Boolean set(String key, String value) {
        return getJedisPoolInstance().getResource().set(key, value).equals("OK");
    }

    public static String get(String key) {
        return getJedisPoolInstance().getResource().get(key);
    }

}
